package com.hxl.tech.gateway.auth.oauth;


import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;
import org.springframework.security.oauth2.provider.token.store.KeyStoreKeyFactory;
import javax.sql.DataSource;
import java.security.KeyPair;


/**
 * 授权服务器配置
 * @author soliddq
 * @date 2023-10-14
 */
@Configuration
@EnableAuthorizationServer
@RequiredArgsConstructor
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {

    @Value("${spring.profiles.active:default}")
    private String profile;

    private final UserAuthService userAuthService;
    private final OAuthApplicationService oAuthApplicationService;
    private final MyJwtAccessTokenConverter converter;
    private final DataSource dataSource;

    // 密钥配置
    @Bean
    public KeyPair keyPair() {
        return new KeyStoreKeyFactory(
                new ClassPathResource(profile+".jks"), "HXL-OPEN".toCharArray())
                .getKeyPair("HXL-OPEN");
    }

    // JWT Token配置
    @Bean
    public JwtTokenStore jwtTokenStore() {
        MyJwtTokenStore tokenStore = new MyJwtTokenStore(jwtAccessTokenConverter(keyPair()));
        tokenStore.setApprovalStore(approvalStore());
        return tokenStore;
    }

    // 授权存储配置
    @Bean
    public MyJdbcApprovalStore approvalStore() {
        MyJdbcApprovalStore approvalStore = new MyJdbcApprovalStore(dataSource);
        approvalStore.setHandleRevocationsAsExpiry(true);
        return approvalStore;
    }

    // Client信息配置为Application
    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {

        clients.withClientDetails(oAuthApplicationService);
    }


    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) {
        endpoints
                .userDetailsService(userAuthService)
                .reuseRefreshTokens(false)
                .accessTokenConverter(jwtAccessTokenConverter(keyPair()))
                .tokenStore(jwtTokenStore());
    }

    private MyJwtAccessTokenConverter jwtAccessTokenConverter(KeyPair keyPair) {
        converter.setKeyPair(keyPair);
        return converter;
    }




}